package com.study.designmodes.service.liabilityChain.v2;

import com.study.designmodes.service.liabilityChain.v1.PreparationList;
import com.study.designmodes.service.liabilityChain.v1.Study;

import java.util.ArrayList;
import java.util.List;

/**
 * 过滤器链
 * FilterChain，也就是责任链，是用于串起所有的责任对象的，它也是StudyPrepareFilter的一个子类
 *
 * @author yangyanbin
 * @date 2023/03/21
 * @since 20230321
 */
public class FilterChain implements StudyPrepareFilter {

    private int pos = 0;

    private Study study;

    private List<StudyPrepareFilter> studyPrepareFilterList;

    public FilterChain(Study study) {
        this.study = study;
    }

    public void addFilter(StudyPrepareFilter studyPrepareFilter) {
        if (studyPrepareFilterList == null) {
            studyPrepareFilterList = new ArrayList<StudyPrepareFilter>();
        }
        studyPrepareFilterList.add(studyPrepareFilter);
    }

    /**
     * 有一个计数器，假设所有的StudyPrepareFilter没有调用完毕，那么调用下一个，否则执行Study的study()方法。
     *
     * @param preparationList 准备工作清单
     * @param filterChain     过滤器链
     */
    @Override
    public void doFilter(PreparationList preparationList, FilterChain filterChain) {
        // 所有过滤器执行完毕
        if (pos == studyPrepareFilterList.size()) {
            study.study();
            return;
        }

        // 每次执行任务+1
        studyPrepareFilterList.get(pos++).doFilter(preparationList, filterChain);

    }
}
